<template>
  <view>
    <scroll-view>
      <div class="wrapper">
        <div class="wrapper__background" />
        <!-- 头部 -->
        <div class="wrapper__head">
          <div class="wrapper__user" @click="onEditClick">
            <div class="wrapper__user-info">
              <div class="wrapper__user-name">{{ userName }}</div>
              <div class="wrapper__user-role">{{ userRoleName }}</div>
            </div>
            <div class="wrapper__user-edit">
              <img class="wrapper__photo" :src="userAvatar" />
            </div>
          </div>
        </div>
        <!-- 操作班级 -->
        <!-- 放到莆田正式环境，这两个是静态或未开发或废弃的。先隐藏 -->
        <template v-if="false">
          <div v-if="userRoleCode === 'headmaster'" class="wrapper__handle wrapper__handle--class">
            <div class="wrapper__handle-content">
              <div>
                <p class="num">40</p>
                <p class="status">已入班</p>
              </div>
              <div>
                <p class="num">40</p>
                <p class="status">未入班</p>
              </div>
            </div>
          </div>
          <div v-if="userHandleList.length > 0" class="wrapper__handle wrapper__handle--mine">
            <div class="wrapper__handle-content">
              <div v-for="(item, index) in userHandleList" :key="index">
                <a href="javascript:;" @click="onHandleItemClick(item)">
                  <img class="icon" :src="item.icon" />
                  <p class="text">{{ item.title }}</p>
                </a>
              </div>
            </div>
          </div>
        </template>
        <!-- 菜单 -->
        <div class="wrapper__user-item">
          <ul v-for="(group, index$1) in userMenuItemList" :key="index$1" class="wrapper__item-ul">
            <li v-for="(item, index) in group" :key="index">
              <a href="javascript:;" @click="onItemClick(item)">
                <div class="item-div">
                  <div class="item-div__left">
                    <img :src="item.icon" alt="" class="item-div__icon" />
                  </div>
                  <div class="item-div__center">
                    <span class="item-div__title">{{ item.title }}</span>
                  </div>
                  <div class="item-div__right">
                    <img
                      class="item-div__go-right"
                      src="~@assets/images/mine/icon/go-right@2x.png"
                    />
                  </div>
                </div>
              </a>
            </li>
          </ul>
        </div>
      </div>
    </scroll-view>

    <!-- 选择用户角色 -->
    <choose-role-popup v-model="showRolePopup" close-on-click-overlay />
  </view>
</template>

<script>
  import { mapGetters } from 'vuex';
  import { getUrlParams, isEmpty } from '@common/util';
  import { phoneVerifyCode } from '@api/visitor';
  import { getUserInfo } from '@common/auth';
  import DefaultUserAvatar from '@static/logo.png';
  import ChooseRolePopup from '@components/home/components/choose-role-popup';

  export default {
    name: 'user',
    components: { ChooseRolePopup },
    data() {
      const MANAGER_ROLES_LIST = [
        'yearlength',
        'subjectleader',
        'headmaster',
        'teacher',
        'office',
        'room'
      ]; // 管理者角色列表
      return {
        handleList: [
          {
            icon: require('@assets/images/menu/todo/icon/audit@2x.png'),
            title: '我的审批',
            url: './user/developing',
            rolePermission: MANAGER_ROLES_LIST
          },
          {
            icon: require('@assets/images/menu/todo/icon/audit@2x.png'),
            title: '我的放行码',
            url: './user/my-access-code',
            rolePermission: MANAGER_ROLES_LIST
          },
          {
            icon: require('@assets/images/menu/todo/icon/audit@2x.png'),
            title: '我的发布',
            url: './user/developing',
            rolePermission: ['headmaster']
          }
        ],
        menuItemList: [
          [
            {
              icon: require('@assets/images/mine/icon/face-collect@2x.png'),
              title: '我的课程表',
              url: './user/developing',
              rolePermission: MANAGER_ROLES_LIST
            },
            {
              icon: require('@assets/images/mine/icon/code@2x.png'),
              title: '扫描通行',
              code: 'wxScanQRCode'
            },
            {
              icon: require('@assets/images/mine/icon/face-collect@2x.png'),
              title: '人脸采集',
              url: './user/face-collect'
            }
          ],
          [
            {
              icon: require('@assets/images/mine/icon/collection@2x.png'),
              title: '收藏',
              url: './user/developing'
            },
            {
              icon: require('@assets/images/mine/icon/password@2x.png'),
              title: '密码重置',
              url: './user/get-verification-code'
            },
            {
              icon: require('@assets/images/mine/icon/face-collect@2x.png'),
              title: '孩子资料',
              url: './user/children-list',
              rolePermission: ['family', 'supermanager']
            },
            {
              icon: require('@assets/images/mine/icon/password@2x.png'),
              title: '帮助中心',
              url: './user/developing'
            }
          ],
          [
            {
              icon: require('@assets/images/mine/icon/choose-role@2x.png'),
              title: '切换身份',
              code: 'userRole'
            }
          ],
          []
        ],
        showRolePopup: false,
        userHandleList: [],
        userMenuItemList: []
      };
    },
    computed: {
      ...mapGetters('wechat', ['isConfigSuccess']),
      ...mapGetters('user', ['userInfo', 'userRole']),
      userName() {
        const { userName, loginName } = this.userInfo;

        return userName || loginName;
      },
      userRoleCode() {
        const { userRole } = this;

        return !isEmpty(userRole) ? userRole.roleCode : '';
      },
      userRoleName() {
        const { userRole } = this;

        return !isEmpty(userRole) ? userRole.roleName : '';
      },
      userAvatar() {
        return this.userInfo.photo || DefaultUserAvatar;
      }
    },
    watch: {
      userRole: 'handleFilterMenu'
    },
    mounted() {
      this.handleFilterMenu();
    },
    methods: {
      // 根据角色进行菜单过滤
      handleFilterMenu() {
        this.userHandleList = this.handleList.filter((item) => {
          return (
            !item.rolePermission ||
            (item.rolePermission && item.rolePermission.includes(this.userRoleCode))
          );
        });
        this.userMenuItemList = [];
        this.menuItemList.forEach((itemArray) => {
          const itemList = itemArray.filter((item) => {
            return (
              !item.rolePermission ||
              (item.rolePermission && item.rolePermission.includes(this.userRoleCode))
            );
          });
          this.userMenuItemList.push(itemList);
        });
      },
      // 扫描结果处理
      handleScanMessage(result) {
        const _self = this;
        const params = getUrlParams(result);
        if (params && params.placeId && params.equCode && params.timeStamp && params.onlineStatus) {
          const { onlineStatus } = params;
          if ([0, '0'].includes(onlineStatus)) {
            return _self.$toast('该设备处于离线状态，暂不支持扫码校验');
          } else {
            // 请求后端校验的方法
            const reqData = {
              ...params,
              userId: getUserInfo().placeUserId
            };
            phoneVerifyCode(reqData).then((res) => {
              const { success, msg } = res;
              _self.$toast(msg);
            });
          }
        } else {
          _self.$toast('扫码的信息有误，请扫描正确的二维码');
        }
      },
      // 微信扫码
      openWxScan() {
        const _self = this;
        if (_self.isConfigSuccess === null) return console.warn('微信config未配置');
        if (_self.isConfigSuccess === false) return console.warn('微信config配置错误');
        wx.scanQRCode({
          needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
          scanType: ['qrCode'], // 可以指定扫二维码qrCode还是一维码barCode，默认二者都有
          success: function (res) {
            console.log('扫描的结果:', res.resultStr);
            _self.handleScanMessage(res.resultStr); // 返回结果处理
          },
          error: function (err) {
            _self.$toast(err);
          }
        });
      },
      onEditClick() {
        this.$router.push('./user/user-info');
      },
      onItemClick(item) {
        if (item.code === 'userRole') {
          return (this.showRolePopup = true);
        } else if (item.code === 'wxScanQRCode') {
          return this.openWxScan();
        } else if (item.url) {
          this.$router.push(item.url);
        }
      },
      onHandleItemClick({ url }) {
        this.$router.push(url);
      }
    }
  };
</script>

<style scoped lang="less">
  @import '~@styles/var';

  .wrapper {
    --handle-class-box-height: 90px;
    --handle-mine-box-height: 110px;

    display: flex;
    display: -webkit-flex;
    flex-direction: column;
    width: 100vw;
    //height: calc(100vh - 50px);
    padding: 0 0 20px 0;
    text-align: center;
    background: #fff;

    &__background {
      position: absolute;
      top: 0;
      left: 0;
      z-index: 1;
      width: 100vw;
      height: 180px;
      background: url('~@assets/images/mine/icon/background@2x.png') no-repeat center center/cover;
    }

    &__head {
      z-index: 1;
      width: 100vw;
      height: 130px;
      text-align: left;
    }
    &__user {
      display: flex;
      display: -webkit-flex;
      flex-direction: row;
      padding: 50px 40px 0 40px;
      color: #fff;
    }
    &__user-info {
      width: 50vw;
      height: 60px;
      margin: auto;
    }

    &__user-edit {
      width: 50vw;
      height: 60px;
      text-align: right;
    }
    &__handle--class {
      height: var(--handle-class-box-height);
    }
    &__handle--mine {
      height: var(--handle-mine-box-height);
    }

    &__handle {
      z-index: 2;
      width: calc(100vw - 50px);
      margin: 0 25px 15px 25px;
      background: #fff;
      border: 1px solid #ebe9e9;
      border-radius: 10px;
      box-shadow: 0 3px 24px 0 rgba(0, 0, 0, 0.04);

      p {
        padding: 0;
        margin: 0;
      }
      .num {
        font-size: 24px;
        font-weight: bold;
        line-height: 30px;
        color: #4ea7f7;
      }
      .status {
        font-size: 14px;
        font-weight: 500;
        line-height: 20px;
        color: #333;
      }
      .text {
        font-size: 12px;
        font-weight: 500;
        line-height: 24px;
        color: #333;
      }
      .icon {
        width: 50px;
        height: 50px;
        clip-path: circle(50% at 50% 50%);
        object-fit: cover;
      }
    }

    &__handle-content {
      display: flex;
      display: -webkit-flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-between;
      width: 100%;
    }

    &__handle--class &__handle-content {
      width: 40%;
      height: var(--handle-class-box-height);
      margin: 0 30%;
    }

    &__handle--mine &__handle-content {
      width: calc(100% - 60px);
      height: var(--handle-mine-box-height);
      margin: 0 30px;
    }

    &__user-item {
      flex: auto;
      padding-top: 50px;
    }

    &__handle--mine + &__user-item {
      padding-top: 0 !important;
    }

    &__photo {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      object-fit: cover;
    }

    &__info {
      padding: 18px 0;
    }

    &__user-name {
      width: calc(60px + 2 * 28px);
      padding: 15px 0 5px 0;
      font-size: 18px;
      font-weight: bold;
      line-height: 18px;
    }

    &__user-role {
      width: calc(60px + 2 * 28px);
      font-size: 14px;
      font-weight: 400;
      line-height: 14px;
    }
    &__edit {
      display: inline-block;
      width: 100%;
      height: 50px;
      padding-right: 18px;
      line-height: 50px;
      text-align: right;
      vertical-align: middle;

      p {
        font-size: 15px;
        font-weight: 400;
        color: rgba(115, 117, 124, 1);
      }
    }

    &__go-right {
      width: 18px;
      padding-left: 11px;
    }

    &__item-ul {
      --item-height: 54px;

      width: 100%;

      &:not(:first-child) {
        // 新设计的我的界面不要这个分割线了
        // border-top: 10px solid #f7f7f7;
      }

      li {
        width: 100%;
        height: var(--item-height);
        padding: 0 15px 0 18px;
        line-height: var(--item-height);
        background: #fff;
      }

      a {
        display: inline-block;
        width: 100%;
        height: var(--item-height);
        line-height: var(--item-height);
        vertical-align: middle;
      }

      .item-div {
        display: flex;
        display: -webkit-flex;
        flex-direction: row;
        height: var(--item-height);
        line-height: var(--item-height);

        &__left {
          width: 37px;
          text-align: left;
        }

        &__center {
          flex: auto;
          text-align: left;
        }

        &__right {
          width: 27px;
        }

        &__icon {
          position: relative;
          top: 8px;
          width: 26px;
          height: 26px;
        }

        &__title {
          font-size: 16px;
          font-weight: 500;
          color: rgba(23, 23, 25, 1);
          text-align: left;
        }

        &__go-right {
          position: relative;
          width: 18px;
          padding-left: 11px;
          text-align: right;
        }
      }
    }
  }
</style>
